<template>
  <view class="time-page">
    

    <scroll-view class="main-content" scroll-y>
      <!-- 今日活动 -->
      <view
        :is-shadow="true" 
        :border="false" 
        margin="16px" 
        padding="0"
        class="section-card"
      >

          <view class="section-title">
            <text class="title-text">今日活动</text>
          </view>

        
        <view class="activities-list">
          <!-- 正在进行的活动 -->
          <view 
            v-for="(activity, index) in activities"
            :key="activity.id"
            :class="['activity-card', `${activity.status}-card`]"
          >
            <view class="activity-item">
              <view class="activity-left">
                <view :class="['activity-icon', activity.category]">
                  <text :class="['fas', getIcon(activity.category), 'activity-fa-icon']"></text>
                </view>
                <view class="activity-details">
                  <text class="activity-name">{{ activity.name }}</text>
                  <text class="activity-time">
                    <template v-if="activity.status === 'running'">
                      已进行: <text class="time-highlight running">{{ formatDuration(activity.duration) }}</text>
                    </template>
                    <template v-else-if="activity.status === 'paused'">
                      已暂停: <text class="time-highlight paused">{{ formatDuration(activity.duration) }}</text>
                    </template>
                    <template v-else-if="activity.status === 'completed'">
                      时长: {{ activity.duration / 60 }}分钟
                    </template>
                  </text>
                </view>
              </view>
              <text 
                v-if="activity.status === 'running'"
                class="fas fa-pause-circle activity-action-icon running-action"
                @tap="pauseActivity(index)"
              ></text>
              <text 
                v-else-if="activity.status === 'paused'"
                class="fas fa-play-circle activity-action-icon paused-action"
                @tap="resumeActivity(index)"
              ></text>
              <text v-else-if="activity.status === 'completed'" class="time-range">{{ activity.timeRange }}</text>
            </view>
          </view>
        </view>


      <!-- 时间分配图表 -->
          <view class="section-title">
            <text class="title-text">时间分配 (今日)</text>
          </view>

        
        <view class="chart-container">
          <l-echart ref="timeChart" @finished="initChart" custom-style="height: 200px;"></l-echart>
        </view>
      </view>


    </scroll-view>

    <!-- 浮动操作按钮 -->
    <uni-fab
      ref="fab"
      :pattern="pattern"
      :content="content"
      :horizontal="'right'"
      :vertical="'bottom'"
      :direction="'horizontal'"
      @trigger="trigger"
      @fabClick="fabClick"
    ></uni-fab>

    
  </view>
</template>

<script>
// nvue 不需要引入
// #ifdef VUE2
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min';
// #endif
// #ifdef VUE3
// #ifdef MP
// 由于vue3 使用vite 不支持umd格式的包，小程序依然可以使用，但需要使用require
const echarts = require('../../static/echarts.min');
// #endif
// #ifndef MP
// 由于 vue3 使用vite 不支持umd格式的包，故引入npm的包
import * as echarts from 'echarts/dist/echarts.esm';
// #endif
// #endif

export default {
  data() {
    return {
      // uni-fab 配置
      pattern: {
        color: '#FFFFFF',
        backgroundColor: '#6366F1',
        selectedColor: '#6366F1',
        buttonColor: '#6366F1',
        iconColor: '#FFFFFF'
      },
      content: [],
      runningTime: '01:23:45',
      pausedTime: '00:15:30',
      totalTime: '3h 45m',
      activeCount: 3,
      avgTime: '1h 15m',
      timer: null,
      chartData: [],
      activities: [
        {
          id: 1,
          name: '工作 - 项目A',
          category: 'work',
          status: 'running',
          duration: 5025, // 秒数
          startTime: '08:30',
          color: '#3B82F6'
        },
        {
          id: 2,
          name: '学习 - 专业课程',
          category: 'study',
          status: 'completed',
          duration: 2700, // 45分钟
          timeRange: '09:00 - 09:45',
          color: '#8B5CF6'
        },
        {
          id: 3,
          name: '运动 - 健身房',
          category: 'exercise',
          status: 'paused',
          duration: 930, // 15分30秒
          startTime: '10:00',
          color: '#10B981'
        }
      ]
    }
  },
  // 处理导航栏按钮点击事件
    onNavigationBarButtonTap(e) {
      if (e.index === 0) { // 设置按钮
        this.goToSettings();
      }
    },
  mounted() {
    this.generateActivities(0) // 生成10条活动数据
    this.startTimer()
    
 
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    generateActivities(count) {
      const categories = ['work', 'study', 'exercise', 'hobby', 'rest']
      const icons = {
        work: 'fa-briefcase',
        study: 'fa-book',
        exercise: 'fa-dumbbell',
        hobby: 'fa-paint-brush',
        rest: 'fa-bed'
      }
      const statusOptions = ['running', 'paused', 'completed']
      const names = {
        work: ['项目A', '会议准备', '文档编写', '代码开发'],
        study: ['专业课程', '英语学习', '技术文档阅读', '在线讲座'],
        exercise: ['健身房', '跑步', '瑜伽', '游泳'],
        hobby: ['绘画', '阅读', '音乐', '园艺'],
        rest: ['午休', '冥想', '小憩']
      }

      for (let i = 0; i < count; i++) {
        const category = categories[Math.floor(Math.random() * categories.length)]
        const status = statusOptions[Math.floor(Math.random() * statusOptions.length)]
        const name = names[category][Math.floor(Math.random() * names[category].length)]
        const duration = Math.floor(Math.random() * 120 * 60) + 600 // 10分钟到2小时之间
        const startHour = Math.floor(Math.random() * 10) + 8 // 8点到17点之间
        const startMinute = Math.floor(Math.random() * 60)
        const endHour = startHour + Math.floor(duration / 3600)
        const endMinute = startMinute + Math.floor((duration % 3600) / 60)

        this.activities.push({
          id: i + 1,
          name: `${category === 'work' ? '工作' : category === 'study' ? '学习' : category === 'exercise' ? '运动' : category === 'hobby' ? '爱好' : '休息'} - ${name}`,
          category: category,
          status: status,
          duration: duration,
          startTime: `${startHour.toString().padStart(2, '0')}:${startMinute.toString().padStart(2, '0')}`,
          timeRange: `${startHour.toString().padStart(2, '0')}:${startMinute.toString().padStart(2, '0')} - ${endHour.toString().padStart(2, '0')}:${endMinute.toString().padStart(2, '0')}`,
          icon: icons[category]
        })
      }
      this.updateStats()
    },
    getIcon(category) {
      const icons = {
        work: 'fa-briefcase',
        study: 'fa-book',
        exercise: 'fa-dumbbell',
        hobby: 'fa-paint-brush',
        rest: 'fa-bed'
      }
      return icons[category] || 'fa-question-circle' // 默认图标
    },
    startTimer() {
      this.timer = setInterval(() => {
        // 更新正在运行的活动时间
        const runningActivity = this.activities.find(a => a.status === 'running')
        if (runningActivity) {
          runningActivity.duration += 1
          // this.runningTime = this.formatDuration(runningActivity.duration) // 直接在模板中使用 formatDuration
          this.updateStats() // 更新统计数据
        }
      }, 1000)
    },
    formatDuration(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },
    updateStats() {
      const totalSeconds = this.activities.reduce((sum, activity) => {
        return sum + (activity.status === 'completed' ? activity.duration : 0)
      }, 0)
      
      const completedCount = this.activities.filter(a => a.status === 'completed').length
      
      this.totalTime = this.formatTime(totalSeconds)
      this.activeCount = this.activities.length
      this.avgTime = completedCount > 0 ? this.formatTime(Math.floor(totalSeconds / completedCount)) : '0m'
      
      // 更新图表数据
      if (this.$refs.timeChart) {
        this.updateChartData()
        this.$refs.timeChart.setChart((chart) => {
          chart.setOption({
            series: [{
              data: this.chartData
            }]
          })
        })
      }
    },
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      
      if (hours > 0) {
        return `${hours}h ${minutes}m`
      }
      return `${minutes}m`
    },
    showDatePicker() {
      uni.showActionSheet({
        itemList: ['今天', '昨天', '本周', '本月', '自定义'],
        success: (res) => {
          const options = ['今天', '昨天', '本周', '本月', '自定义']
          uni.showToast({
            title: `已切换到${options[res.tapIndex]}`, 
            icon: 'none'
          })
        }
      })
    },
    goToSettings() {
      uni.navigateTo({
        url: '/pages/settings/index'
      })
    },
    
    
    pauseActivity(index) {
      const activity = this.activities[index]
      if (activity && activity.status === 'running') {
        activity.status = 'paused'
        uni.showToast({
          title: '活动已暂停',
          icon: 'success'
        })
      }
    },
    resumeActivity(index) {
      const activity = this.activities[index]
      if (activity && activity.status === 'paused') {
        // 先暂停其他正在运行的活动
        this.activities.forEach(a => {
          if (a.status === 'running') {
            a.status = 'paused'
          }
        })
        
        activity.status = 'running'
        uni.showToast({
          title: '活动已恢复',
          icon: 'success'
        })
      }
    },
    fabClick() {
      console.log('FAB clicked');
      uni.navigateTo({
        url: '/pages/time/record'
      })
    },
    trigger(e) {
      console.log(e);
    },
    startNewActivity() {
      uni.navigateTo({
        url: '/pages/time/record'
      })
    },
    initChart() {
      this.updateChartData()
      this.$nextTick(() => {
        this.$refs.timeChart.init(echarts, (chart) => {
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c}分钟 ({d}%)'
            },
            legend: {
              orient: 'horizontal',
              bottom: '0%',
              textStyle: {
                fontSize: 12
              }
            },
            series: [
              {
                name: '时间分配',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '16',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: this.chartData
              }
            ]
          }
          chart.setOption(option)
        })
      })
    },
    updateChartData() {
      const categoryStats = {}
      const categoryColors = {
        work: '#3B82F6',
        study: '#8B5CF6', 
        exercise: '#10B981',
        hobby: '#EF4444',
        rest: '#F59E0B'
      }
      const categoryNames = {
        work: '工作',
        study: '学习',
        exercise: '运动', 
        hobby: '爱好',
        rest: '休息'
      }
      
      // 统计各类别的时间
      this.activities.forEach(activity => {
        if (activity.status === 'completed') {
          const category = activity.category
          const minutes = Math.round(activity.duration / 60)
          if (!categoryStats[category]) {
            categoryStats[category] = 0
          }
          categoryStats[category] += minutes
        }
      })
      
      // 转换为图表数据格式
      this.chartData = Object.keys(categoryStats).map(category => ({
        name: categoryNames[category] || category,
        value: categoryStats[category],
        itemStyle: {
          color: categoryColors[category] || '#9CA3AF'
        }
      }))
      
      // 如果完成的活动数据太少，显示示例数据
      if (this.chartData.length <= 1) {
        this.chartData = [
          { name: '工作', value: 120, itemStyle: { color: '#3B82F6' } },
          { name: '学习', value: 45, itemStyle: { color: '#8B5CF6' } },
          { name: '运动', value: 30, itemStyle: { color: '#10B981' } },
          { name: '休息', value: 15, itemStyle: { color: '#F59E0B' } }
        ]
      }
    },
    goToPage(page) {
      uni.switchTab({
        url: `/pages/${page}/index`
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/static/css/fontawesome.min.css';
@import '@/static/css/brands.min.css';
@import '@/static/css/solid.min.css';

page {
  background-color: #F0F2F5;
}

.time-page {
  min-height: 100vh;
  background-color: #FFFFFF;
  padding-bottom: 60px; /* 底部导航栏高度 */
}

.nav-bar {
  /* #ifndef H5 */
  padding-top: 20px; /* Adjust for status bar */
  /* #endif */
  .nav-right-icons {
    display: flex;
    align-items: center;
    .nav-icon {
      font-size: 20px;
      color: #6B7280;
      margin-left: 15px;
    }
  }
}

.main-content {
  padding-top: 0;
  padding-bottom: 32px;
  min-height: calc(100vh - var(--window-top) - var(--window-bottom) - 60px); /* 减去底部导航栏高度 */
  background-color: #FFFFFF;
}

.section-card {
  // border-radius: 12px;
  overflow: hidden;
  // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  &:last-child {
    margin-bottom: 80px; /* 确保底部有足够空间 */
  }
}

/* 分组标题 */
.section-title {
  display: flex;
  align-items: center;
  padding: 16px;
  // border-bottom: 1px solid #F0F2F5;
  .title-text {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
}

/* 活动列表 */
.activities-list {
  padding: 0;
}

.activity-card {
  margin: 0 16px 12px 16px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  &:last-child {
    margin-bottom: 0;
  }
}

.activity-card.running-card {
  border-left: 4px solid #10B981;
}

.activity-card.paused-card {
  border-left: 4px solid #F59E0B;
}

.activity-card.completed-card {
  border-left: 4px solid #8B5CF6;
}

.activity-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  min-height: 64px;
  background-color: #F9FAFB;
}

.activity-card.running-card .activity-item {
  background-color: #ECFDF5;
}

.activity-card.paused-card .activity-item {
  background-color: #FFFBEB;
}

.activity-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  .activity-fa-icon {
    font-size: 18px;
  }
}

.activity-icon.work {
  background-color: #DBEAFE;
  .activity-fa-icon {
    color: #3B82F6;
  }
}

.activity-icon.study {
  background-color: #EDE9FE;
  .activity-fa-icon {
    color: #8B5CF6;
  }
}

.activity-icon.exercise {
  background-color: #D1FAE5;
  .activity-fa-icon {
    color: #10B981;
  }
}

.activity-icon.hobby {
  background-color: #FEE2E2;
  .activity-fa-icon {
    color: #EF4444;
  }
}

.activity-icon.rest {
  background-color: #E0F2FE;
  .activity-fa-icon {
    color: #3B82F6;
  }
}

.activity-details {
  flex: 1;
}

.activity-name {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 2px;
}

.activity-time {
  font-size: 13px;
  color: #6B7280;
  display: block;
}

.time-highlight {
  font-weight: 600;
}

.time-highlight.running {
  color: #10B981;
}

.time-highlight.paused {
  color: #F59E0B;
}

.time-range {
  font-size: 13px;
  color: #6B7280;
}

.activity-action-icon {
  font-size: 28px;
  cursor: pointer;
  &.running-action {
    color: #10B981;
  }
  &.paused-action {
    color: #F59E0B;
  }
}

/* 图表容器 */
.chart-container {
  padding: 16px;
}

.chart-placeholder {
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9CA3AF;
  background-color: #F9FAFB;
  border-radius: 8px;
  border: 1px dashed #D1D5DB;
  .chart-icon {
    font-size: 40px;
    color: #9CA3AF;
  }
}

.chart-text {
  font-size: 13px;
  margin-top: 6px;
  color: #6B7280;
}

/* 统计网格 */
.stats-grid {
  display: flex;
  justify-content: space-around;
  padding: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-value {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #6B7280;
  text-align: center;
}

/* 底部导航栏 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 60px;
  background-color: #FFFFFF;
  border-top: 1px solid #F0F0F0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  z-index: 1000;
}

.tab-bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  color: #9CA3AF;
  font-size: 12px;
  &.active {
    color: #4F46E5; /* 主题色 */
    .tab-icon {
      color: #4F46E5;
    }
  }
}

.tab-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.tab-text {
  font-size: 11px;
}



/* 响应式调整 */
@media screen and (max-width: 375px) {
  .activity-icon {
    width: 36px;
    height: 36px;
  }
  
  .activity-name {
    font-size: 14px;
  }
  
  .activity-time {
    font-size: 12px;
  }
  
  .stat-value {
    font-size: 16px;
  }
  
  .tab-icon {
    font-size: 18px;
  }
  
  .tab-text {
    font-size: 10px;
  }
  

}
</style>